<template>
  <a-row :gutter="7">
    <a-col :md="6" :sm="24">
      <a-card :bordered="false" style="height: 720px">
        <div style="background: #fff;padding-left:2px;height: 100%; margin-top: 0px">
          <a-row>
            <a-col :span="24">
              <a-button @click="handleAdd(1)" type="primary">添加工作中心</a-button>
              <a-button @click="handleAdd(2)" type="primary" style="margin-left: 5px">添加下级</a-button>
              <a-button @click="handleDeleteBatch()" style="margin-left: 5px">批量删除</a-button>
            </a-col>
          </a-row>
          <a-row style="margin-top: 10px">
            <a-col :span="24">
              <a-input-search @search="onSearch" style="width:100%" placeholder="请输入工作中心名称"/>
            </a-col>
          </a-row>
          <a-spin :spinning="treeLoading">
            <template v-if="treeData.length>0">
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
              <span style="user-select: none">
                    <a-tree
                      checkable
                      multiple
                      :replaceFields="{children:'childList', title:'name', key:'id'}"
                      :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
                      @select="handleTreeSelect"
                      @check="handleTreeCheck"
                      @rightClick="rightHandle"
                      :checkStrictly="checkStrictly"
                      :selectedKeys="selectedKeys"
                      :checkedKeys="checkedKeys"
                      :treeData="treeData"
                      :autoExpandParent="autoExpandParent"
                      :expandedKeys="treeExpandedKeys"
                      @expand="handleTreeExpand"/>
                  </span>
                <a-menu slot="overlay">
                  <a-menu-item @click="handleAdd(3)" key="1">添加</a-menu-item>
                  <a-menu-item @click="handleDelete" key="2">删除</a-menu-item>
                  <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
            <template v-else>
              <a-empty style="margin-top: 20px"/>
            </template>
          </a-spin>
        </div>
      </a-card>
      <div class="drawer-bootom-button">
        <a-dropdown :trigger="['click']" placement="topCenter">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
            <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
            <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
            <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
            <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
            <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
          </a-menu>
          <a-button>
            树操作
            <a-icon type="up"/>
          </a-button>
        </a-dropdown>
      </div>
    </a-col>
    <a-col :md="18" :sm="24">
      <a-spin :spinning="detailLoading">
        <a-card :bordered="false" title="工作中心详情" style="height: 777px">
          <a-button @click="handleSave" slot="extra" type="primary">保 存</a-button>
          <j-form-container :disabled="false">
            <a-form-model ref="form" :model="selectedData" :rules="validatorRules" slot="detail">
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                    <a-input v-model="model.code" placeholder="请输入编码"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                    <a-input v-model="model.name" placeholder="请输入名称"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="简称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shortName">
                    <a-input v-model="model.shortName" placeholder="请输入简称"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="工厂" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="factoryId">
                    <j-dict-select-tag type="list" v-model="model.factoryId" dictCode="mdm_factory,factory_name,id"
                                       placeholder="请选择工厂" @change="factoryChange"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companyId">
                    <j-dict-select-tag type="list" v-model="model.companyId" dictCode="mdm_company,company_name,id"
                                       placeholder="请选择公司"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="编制人数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="postNum">
                    <a-input-number v-model="model.postNum" placeholder="请输入编制人数" style="width: 100%"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="操作范围" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workScope">
                    <j-dict-select-tag type="list" v-model="model.workScope" dictCode="mdm_work_scope"
                                       placeholder="请选择操作范围"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="产品线" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productLineId">
                    <j-dict-select-tag type="list" v-model="model.productLineId" dictCode="mdm_product_line,name,id"
                                       placeholder="请选择产品线"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </j-form-container>
          <a-row>
            <a-col :span="24" :style="{textAlign: 'right'}">
              <a :style="{ marginLeft: '8px', fontSize: '14px' }" @click="handleEdit">
                <a-icon type="edit"/>
                更多信息
              </a>
            </a-col>
          </a-row>
          <a-tabs defaultActiveKey="1">
            <a-tab-pane tab="子工作中心" :key="refKeys[0]" :forceRender="true">
              <a-card :bordered="false" :body-style="{padding: '0px 3px 25px 3px'}">
                <mdm-work-center-list-tab
                  ref="mdmWorkCenterTable"
                  :page-search-hidden="true"
                  :init-query-param="{pid: model.id}"
                  :init-add-model="{pid: model.id}"
                  @ok="workCenterChildCallback"
                />
              </a-card>
            </a-tab-pane>
            <a-tab-pane tab="设备列表" :key="refKeys[1]" :forceRender="true">
              <a-card :bordered="false" :body-style="{padding: '0px 3px 25px 3px'}">
                <mdm-equipment-table
                  ref="mdmEquipmentTable"
                  :page-search-hidden="true"
                  :init-query-param="{pid: model.id}"
                  :init-add-model="{pid: model.id}"
                />
              </a-card>
            </a-tab-pane>
            <a-tab-pane tab="人员列表" :key="refKeys[2]" :forceRender="true">
              <mdm-user-info-table
                ref="mdmUserInfoTable"
                :page-search-hidden="true"
                :init-query-param="{pid: model.id}"
                :init-add-model="{pid: model.id}"
              />
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-spin>
    </a-col>
    <mdm-work-center-modal ref="modalForm" @ok="modalFormOk"></mdm-work-center-modal>
  </a-row>
</template>

<script>

import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {getAction, putAction, httpAction} from "@api/manage";
import {filterMultiDictText} from "@/components/dict/JDictSelectUtil";
import MdmWorkCenterModal from "@/views/mdm/workCenter/modules/MdmWorkCenterModal";
import MdmEquipmentTable from "@/views/mdm/equipment/MdmEquipmentTable";
import MdmUserInfoTable from "@/views/mdm/userInfo/MdmUserInfoTable";
import {deleteAction} from "@/api/manage";
import MdmWorkCenterListTab from "@/views/mdm/workCenter/MdmWorkCenterListTab";
import Template1 from "@/views/jeecg/JVxeDemo/layout-demo/Template1.vue";

export default {
  name: "MdmWorkCenterTree",
  mixins: [JeecgListMixin],
  components: {Template1, MdmWorkCenterListTab, MdmWorkCenterModal,MdmEquipmentTable,MdmUserInfoTable},
  data() {
    return {
      description: '工作中心',
      loading: false,
      detailLoading: false,
      treeLoading: false,
      table01Loading: false,
      table02Loading: false,
      table03Loading: false,
      modelChanged: false,
      checkStrictly: true,
      dropTrigger: '',
      rightClickSelectedKey: '',
      treeData: [],
      allTreeKeys: [],
      selectedKeys: [],
      checkedKeys: [],
      selectedData: {},
      selectedDeviceList: [],
      selectedUserList: [],
      model: {},
      treeExpandedKeys: [],
      treeSearchParam: {},
      autoExpandParent: true,
      refKeys: ['mdmWorkCenterChildren', 'mdmEquipmentList', 'mdmUserInfoList'],
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      // 表头
      allColumns: {
        workCenterColumns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '编码',
            align: "center",
            dataIndex: 'code'
          },
          {
            title: '名称',
            align: "center",
            dataIndex: 'name'
          },
          {
            title: '简称',
            align: "center",
            dataIndex: 'shortName'
          },
          {
            title: '工厂',
            align: "center",
            dataIndex: 'factoryId_dictText'
          },
          {
            title: '公司',
            align: "center",
            dataIndex: 'companyId_dictText'
          },
          {
            title: '编制人数',
            align: "center",
            dataIndex: 'postNum'
          },
          {
            title: '操作范围',
            align: "center",
            dataIndex: 'workScope_dictText'
          },
          {
            title: '所在位置',
            align: "center",
            dataIndex: 'location'
          },
          {
            title: '零配件提取天数',
            align: "center",
            dataIndex: 'partDays'
          },
          {
            title: '零配件下工单',
            align: "center",
            dataIndex: 'partOrderFlag',
            // customRender: (text) => (text ? filterMultiDictText(this.dictOptions['partOrderFlag'], text) : ''),
          },
          {
            title: '检修计划下工单',
            align: "center",
            dataIndex: 'repairOrderFlag',
            // customRender: (text) => (text ? filterMultiDictText(this.dictOptions['repairOrderFlag'], text) : ''),
          },
          {
            title: '扫码方式',
            align: "center",
            dataIndex: 'scanWay_dictText'
          },
          {
            title: '生效日期',
            align: "center",
            dataIndex: 'effectiveDate',
            customRender: function (text) {
              return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
            }
          },
          {
            title: '失效日期',
            align: "center",
            dataIndex: 'expireDate',
            customRender: function (text) {
              return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
            }
          },
          {
            title: '排序',
            align: "center",
            dataIndex: 'sort'
          },
          {
            title: '备注',
            align: "center",
            dataIndex: 'note'
          },
          {
            title: '启用',
            align: "center",
            dataIndex: 'enableFlag',
            // customRender: (text) => (text ? filterMultiDictText(this.dictOptions['enableFlag'], text) : ''),
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 147,
            scopedSlots: {customRender: 'action'}
          }
        ],
        deviceColumns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '编码',
            align: "center",
            dataIndex: 'code'
          },
          {
            title: '名称',
            align: "center",
            dataIndex: 'name'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 147,
            scopedSlots: {customRender: 'action'}
          }
        ],
        userColumns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '员工号',
            align: "center",
            dataIndex: 'code'
          },
          {
            title: '姓名',
            align: "center",
            dataIndex: 'name'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 147,
            scopedSlots: {customRender: 'action'}
          }
        ]
      },
      validatorRules: {
        code: [
          {required: true, message: '请输入编码!'},
        ],
        name: [
          {required: true, message: '请输入名称!'},
        ],
      },
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 18},
      },
      url: {
        edit: "/mdm/workCenter/edit",
        delete: "/mdm/workCenter/delete",
        deleteBatch: "/mdm/workCenter/deleteBatch",
        treeList: "/mdm/workCenter/treeList",
        queryFactoryById: "/mdm/factory/queryById",
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {

  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
    modelData() {
      return JSON.parse(JSON.stringify(this.model))
    },
  },
  watch: {
    modelData: {
      handler(newVal, oldVal) {
        if (newVal.id && newVal.id === oldVal.id && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          this.modelChanged = true;
        }
      },
      deep: true
    }
  },
  methods: {
    loadData() {
      this.loadTree(true);
    },
    loadTree(resetSelected) {
      let that = this;
      that.loading = true;
      that.treeData = [];
      that.allTreeKeys = [];
      that.selectedData = {};
      if (resetSelected) {
        that.selectedKeys = [];
        that.checkedKeys = [];
        that.treeExpandedKeys = [];
      }
      getAction(this.url.treeList, this.treeSearchParam).then(res => {
        if (res.success && res.result) {
          if (!res.result || res.result.length == 0) {
            return;
          }
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            that.getAllKeys(temp);
          }
          if (resetSelected) {
            that.selectedKeys.push(res.result[0].id)
            that.selectedData = res.result[0]
          } else {
            that.selectedData = that.getSelectedData(that.treeData);
          }
          that.model = Object.assign({}, that.selectedData, {childList: []});
        }
      }).finally(() => {
        that.loading = false
      })
    },
    // 树被展开触发的事件
    handleTreeExpand(expandedKeys) {
      this.treeExpandedKeys = expandedKeys
    },
    // 树被选择触发的事件
    handleTreeSelect(selectedKeys, e) {
      let that = this;
      let record = e.node.dataRef;
      if (this.modelChanged) {
        this.checkModelUpdate(record)
      } else {
        that.selectedData = record;
        that.model = Object.assign({}, that.selectedData, {childList: []});
        that.selectedKeys = [record.id]
      }
    },
    checkModelUpdate(selectedNode) {
      if (!this.modelChanged) {
        return;
      }
      this.modelChanged = false;
      let that = this;
      that.$confirm({
        title: "工作中心",
        content: "数据已更新，是否保存?",
        onOk() {
          that.detailLoading = true;
          putAction(that.url.edit, that.model).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              getAction(that.url.treeList, that.treeSearchParam).then(res => {
                if (res.success && res.result) {
                  if (!res.result || res.result.length == 0) {
                    return;
                  }
                  that.treeData = [];
                  that.allTreeKeys = [];
                  for (let i = 0; i < res.result.length; i++) {
                    let temp = res.result[i]
                    that.treeData.push(temp)
                    that.getAllKeys(temp);
                  }
                  if (selectedNode) {
                    that.selectedData = selectedNode;
                    that.selectedKeys = [selectedNode.id]
                  } else {
                    that.selectedData = that.getSelectedData(that.treeData);
                    that.selectedKeys = [that.treeData[0].id]
                  }
                  that.model = Object.assign({}, that.selectedData, {childList: []});
                }
              })
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.detailLoading = false;
          });
        },
        onCancel() {
          if (selectedNode) {
            that.selectedData = selectedNode;
            that.model = Object.assign({}, that.selectedData, {childList: []});
            that.selectedKeys = [selectedNode.id]
          } else {
            that.loadTree(true);
          }
        }
      })
    },

    handleTreeCheck(checkedKeys, info) {
      this.hiding = false
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked;
      } else {
        this.checkedKeys = checkedKeys
      }
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
    },
    setTreeExpandedKeys(node) {
      //只展开一级目录
      if (node.children && node.children.length > 0) {
        this.treeExpandedKeys.push(node.key)
        //下方代码放开注释则默认展开所有节点
        /**
         for (let a = 0; a < node.children.length; a++) {
            this.setTreeExpandedKeys(node.children[a])
          }
         */
      }
    },
    onSearch(value) {
      this.treeSearchParam.name = value || '';
      this.checkedKeys = [];
      if (this.modelChanged) {
        this.checkModelUpdate()
      } else {
        this.loadTree(true);
      }
    },
    moreInfo() {
      this.colHidden = !this.colHidden;
    },
    infoPopupCallback(value, row) {
      this.selectedData = Object.assign(this.selectedData, row);
      this.model = this.selectedData;
    },
    classifyIntoFormData(allValues) {
      return {
        ...this.model, // 展开
        children: allValues.tablesValue[0].values,
      }
    },
    /** 覆盖JEditableTable的方法，原基础上增加刷新树形 */
    request(formData) {
      let url = this.url.add, method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      httpAction(url, formData, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
        this.loadTree();
      })
    },
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键操作方法
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      this.rightClickSelectedKey = node.node.eventKey
    },
    // 右键下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },
    getAllKeys(node) {
      this.allTreeKeys.push(node.id)
      if (node.childList && node.childList.length > 0) {
        for (let a = 0; a < node.childList.length; a++) {
          this.getAllKeys(node.childList[a])
        }
      }
    },
    getSelectedData(treeData) {
      if (!this.selectedKeys || this.selectedKeys.length == 0) {
        return null;
      }
      let curData = null;
      for (let i = 0; i < treeData.length; i++) {
        if (this.selectedData && this.selectedData.id) {
          break;
        }
        let data = treeData[i];
        if (data.id === this.selectedKeys[0]) {
          curData = data
        } else {
          if (data.childList && data.childList.length > 0) {
            curData = this.getSelectedData(data.childList);
          }
        }
        if (curData) {
          break;
        }
      }

      return curData;
    },
    handleEdit() {
      if (!this.model) {
        return;
      }
      this.$refs.modalForm.edit(this.model);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleAdd(num) {
      if (num == 1) {
        this.$refs.modalForm.add();
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
      } else if (num == 2) {
        if (this.selectedKeys.length <= 0) {
          this.$message.error("请先点击选中上级工作中心!")
          return
        }
        this.$refs.modalForm.add(this.selectedKeys[0]);
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
      } else {
        this.$refs.modalForm.add(this.rightClickSelectedKey)
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false;
      }
    },
    handleDelete() {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      let that = this;
      this.$confirm({
        title: '确认删除',
        content: '确定要删除此工作中心以及子节点数据吗?',
        onOk: function () {
          deleteAction(that.url.delete, {id: that.rightClickSelectedKey}).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadTree(true)
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    handleDeleteBatch() {
      if (this.checkedKeys.length <= 0) {
        this.$message.error("请勾选一条记录!")
        return
      }
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      let that = this;
      this.$confirm({
        title: '确认删除',
        content: '确定要删除所选中的 ' + that.checkedKeys.length + ' 条数据，以及子节点数据吗?',
        onOk: function () {
          deleteAction(that.url.deleteBatch, {ids: that.checkedKeys.join(',')}).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadTree(true)
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.model = {}
      this.loadTree(false);
    },
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    closeAll() {
      this.treeExpandedKeys = []
    },
    checkALL() {
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      this.checkedKeys = []
    },
    expandAll() {
      this.treeExpandedKeys = this.allTreeKeys
    },
    handleSave() {
      let that = this;
      that.detailLoading = true;
      putAction(that.url.edit, that.model).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.modelChanged = false;
          that.model = {}
          that.loadTree(false)
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.detailLoading = false;
      });
    },
    workCenterChildCallback() {
      this.loadTree(false)
    },
    factoryChange(factoryId){
      if(!factoryId){
        this.model.companyId = '';
        return;
      }
      getAction(this.url.queryFactoryById, {id: factoryId}).then(res =>{
        if(res.success){
          let factoryData = res.result;
          this.model.companyId = factoryData.companyId;
        }else{
          this.$message.warning(res.message);
        }
      }).finally(() => {
        //
      })
    }
  }
}
</script>
<style lang="less">
/** 隐藏文件小图标 */
.mdm-workCenter-tree.ant-tree {
  li span.ant-tree-switcher.ant-tree-switcher-noop {
    display: none;
  }
}

.drawer-bootom-button {
  /*position: absolute;*/
  bottom: 0;
  width: 100%;
  height: 57px;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>